package login

import (
	"encoding/json"
	"html/template"
	"myfirstweb/com/zgm/db"
	"net/http"
)

func LoginConfirmHandler(w http.ResponseWriter, r *http.Request) {
	locals := make(map[string]interface{})
	r.ParseForm()
	usercode := r.FormValue("usercode")
	password := r.FormValue("password")
	sql := "select * from user where name='" + usercode + "'"
	rows, err := db.Query(sql)
	if err != nil {
		locals["state"] = "fail"
		locals["data"] = err.Error()
	} else {
		if len(rows) > 0 {
			pass, ok := rows[0].(map[string]interface{})
			if ok {
				if pass["password"] == password {
					locals["state"] = "success"
					locals["data"] = rows
				} else {
					locals["state"] = "fail"
					locals["data"] = "密码错误"
				}
			}
		} else {
			locals["state"] = "fail"
			locals["data"] = "用户不存在"
		}
	}
	js, err := json.Marshal(locals)
	defer w.Header().Set("Content-Type", "application/json")
	defer w.Write(js)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
func LoginHandler(w http.ResponseWriter, r *http.Request) {
	locals := make(map[string]interface{})
	t, err := template.ParseFiles("./http/views/login.html")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	t.Execute(w, locals)
}
